package com.xbh.Book.service.impl;

import com.xbh.Book.dao.BookDao;
import com.xbh.Book.dao.OrderDao;
import com.xbh.Book.dao.OrderItemDao;
import com.xbh.Book.dao.impl.BookDaoImpl;
import com.xbh.Book.dao.impl.OrderDaoImpl;
import com.xbh.Book.dao.impl.OrderItemDaoImpl;
import com.xbh.Book.pojo.*;
import com.xbh.Book.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @program: JavaWebExer
 * @description:
 * @author: 许宝华
 * @create: 2021-05-03 14:58
 */

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao=new OrderDaoImpl();
    private OrderItemDao orderItemDao=new OrderItemDaoImpl();
    private BookDao bookDao=new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //订单号要确保唯一性
        String orderId=System.currentTimeMillis()+""+userId;
        //创建一个订单对象
        Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
        //保存订单
        orderDao.saveOrder(order);
//        int i=12/0;//模拟出现异常
        //遍历购物车中每一个商品项转换为订单项保存到数据库中
        for(Map.Entry<Integer, CartItem> entry:cart.getItems().entrySet()){
            //获取每一个购物车中的商品项
            CartItem cartItem=entry.getValue();
            //转换为每一个订单项
            OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            //保存订单项到数据库
            orderItemDao.saveOrderItem(orderItem);

            //图书的库存也要改,更新库存和销量
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookDao.updateBook(book);
        }
        //清空购物车
        cart.clear();
        return orderId;
    }
}
